// ignore_for_file: prefer_const_constructors

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:multi_shop/models/address.dart';
import 'package:multi_shop/models/order_item.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/services/order_api.dart';
import 'package:multi_shop/services/user_api.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:multi_shop/widgets/payDialog.dart';

/// 下单页面（订单确认与提交）
class OrderPage extends StatefulWidget {
  final List<OrderItem> items;
  const OrderPage({Key? key, required this.items}) : super(key: key);

  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> {
  Address? _selectedAddress;
  String get _addressDisplay => _selectedAddress != null
      ? '${_selectedAddress!.receiverName}  ${_selectedAddress!.receiverPhone}\n${_selectedAddress!.province}${_selectedAddress!.city}${_selectedAddress!.district} ${_selectedAddress!.detailAddress}'
      : '请选择收货地址';
  final orderApi = OrderApi();
  final userApi = UserApi();
  UserInfo? userInfo;
  // 获取默认地址
  @override
  void initState() {
    super.initState();
    // 获取用户信息
    userInfo = GetStorage().read<UserInfo>('userInfo');
    _initData();
  }

  Future<void> _initData() async {
    try {
      final addr = await userApi.getDefaultAddress();
      if (!mounted) return;
      setState(() => _selectedAddress = addr); // 可能为 null
    } catch (e) {
      if (!mounted) return;
      setState(() => _selectedAddress = null);
    }
  }

  /// 计算总价
  double get _total =>
      widget.items.fold(0, (sum, item) => sum + item.price * item.quantity);

  Future<void> _chooseAddress() async {
    final result = await Get.toNamed('/address');
    if (result is Address) {
      setState(() {
        _selectedAddress = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('确认订单')),
      body: Column(
        children: [
          // 地址选择
          InkWell(
            onTap: _chooseAddress,
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                children: [
                  Icon(Icons.location_on, color: Colors.redAccent),
                  SizedBox(width: 8),
                  Expanded(child: Text(_addressDisplay)),
                  Icon(Icons.chevron_right),
                ],
              ),
            ),
          ),
          SizedBox(height: 8),

          // 商品列表
          Expanded(
            child: ListView.separated(
              itemCount: widget.items.length,
              separatorBuilder: (_, __) => Divider(height: 1),
              itemBuilder: (context, index) {
                final item = widget.items[index];
                return ListTile(
                  leading: ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: Image.network(
                      item.imageUrl,
                      width: 60,
                      height: 60,
                      fit: BoxFit.cover,
                    ),
                  ),
                  title: Text(
                    item.name,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  subtitle: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '¥${item.price.toStringAsFixed(2)}',
                        style: TextStyle(fontSize: 16, color: Colors.red),
                      ),

                      Text('x ${item.quantity}'),
                    ],
                  ),
                );
              },
            ),
          ),

          // 支付方式 & 总价 & 提交
          Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 支付方式
                Row(
                  children: [
                    Text('支付方式: '),
                    Spacer(),
                    DropdownButton<String>(
                      value: '余额支付',
                      items: ['余额支付']
                          .map(
                            (e) => DropdownMenuItem(value: e, child: Text(e)),
                          )
                          .toList(),
                      onChanged: (val) {},
                    ),
                  ],
                ),
                SizedBox(height: 12),
                // 价格与按钮
                Row(
                  children: [
                    Text('合计: ', style: TextStyle(fontSize: 16)),
                    Expanded(
                      child: Text(
                        '¥${_total.toStringAsFixed(2)}',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.redAccent,
                        ),
                        textAlign: TextAlign.right,
                      ),
                    ),
                    SizedBox(width: 16),
                    SizedBox(
                      height: 44,
                      child: ElevatedButton(
                        onPressed: () {
                          debugPrint('userInfo:${userInfo!.toJson()}');
                          if (_selectedAddress == null) {
                            Get.snackbar('错误', '请选择收货地址');
                            return;
                          }
                          // 未设置支付密码
                          if (userInfo?.hasPayPwd != true) {
                            Get.defaultDialog(
                              title: "提示",
                              middleText: "您还未设置支付密码，请先设置。",
                              textConfirm: "去设置",
                              textCancel: "稍后",
                              confirmTextColor: Colors.white,
                              barrierDismissible: false, // 点遮罩不关闭
                              onConfirm: () {
                                Get.back(); // 先关闭弹窗
                                // 跳转到设置支付密码页面（按你的路由改）
                                Get.to(() => {});
                                // 或：Get.toNamed('/setPayPwd');
                              },
                              onCancel: () {},
                            );
                          }
                          // 判断用户余额是否充足
                          if (userInfo!.balance < _total) {
                            toastCenter("余额不足");
                            return;
                          }
                          debugPrint('开始提交订单');
                          orderApi
                              .submit(
                                items: widget.items,
                                addressId: _selectedAddress!.id!,
                              )
                              .then((value) {
                                if (value["orderNo"] != "") {
                                  showDialog(
                                    context: context,
                                    builder: (_) => PayDialog(
                                      orderNo: value["orderNo"],
                                      amount: _total,
                                      balance: userInfo!.balance,
                                      onConfirm: (method, pwd) {
                                        Get.toNamed(
                                          '/payment_success',
                                          arguments: {
                                            'orderNo': value["orderNo"]!,
                                            'amount': _total,
                                          },
                                        );
                                      },
                                    ),
                                  );
                                }
                              });
                          // Get.toNamed(
                          //   '/payment_success',
                          //   arguments: {'orderId': '123456', 'amount': _total},
                          // );
                        },
                        child: Text('提交订单'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
